package com.hainabo.mgcmall.api.wx;

import com.hainabo.bootside.core.common.ReturnVO;
import com.hainabo.mgcmall.dao.CarOwnerOrderRespository;
import com.hainabo.mgcmall.dao.PassengerOrderRespository;
import com.hainabo.mgcmall.dao.ReleasedRespository;
import com.hainabo.mgcmall.model.Released;
import com.hainabo.mgcmall.util.JsonUtil;
import com.hainabo.mgcmall.util.MapUtil;
import com.spatial4j.core.io.GeohashUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by guoshihao on 2017/12/2.
 */
@Api(value = "/wx/wxOrder")
@Component
@Path("/wx/wxOrder")
@Produces(MediaType.APPLICATION_JSON)
@Slf4j
public class WxOrderResource {

    @Autowired
    private CarOwnerOrderRespository carOwnerOrderRespository;

    @Autowired
    private PassengerOrderRespository passengerOrderRespository;

    @Autowired
    private ReleasedRespository releasedRespository;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @POST
    @Path("add")
    public ReturnVO addOrder(String json) {
        Map param = JsonUtil.toHashMap(json);
        Object object = null;
        Released released = JsonUtil.toBean(param, Released.class);
//        String code = GeohashUtils.encodeLatLon(Double.valueOf(released.getStartlat()), Double.valueOf(released.getStartlng()));
//        System.out.println(code);
        released.setUserId(Long.valueOf(param.get("userId").toString()));
        object = releasedRespository.save(released);
        if (object == null){
            return new ReturnVO("发布出错请重新发布");
        }else {
            return new ReturnVO(object);
        }
    }

    @POST
    @Path("list")
    public ReturnVO getList(String json) {
        Map param = JsonUtil.toHashMap(json);
        Specification specification = new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                String today = param.get("today").toString();
                String start = param.get("start").toString();
                String end = param.get("end").toString();
                if(StringUtils.isNotBlank(today)){
                    predicates.add(criteriaBuilder.equal(root.get("date"),today));
                }
                if(StringUtils.isNotBlank(start)){
                    predicates.add(criteriaBuilder.like(root.get("departure"),"%"+start+"%"));
                }
                if(StringUtils.isNotBlank(end)){
                    predicates.add(criteriaBuilder.like(root.get("destination"),"%"+end+"%"));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        int pageSize = 5;
        int page = ((int) param.get("page") - 1) * pageSize;
        System.out.println(page);
        Page<Released> result= releasedRespository.findAll(specification,new PageRequest(page,pageSize));
        return new ReturnVO(result.getContent());
    }

    @POST
    @Path("conditionList")
    public ReturnVO getConditionList(String json) {
        Map param = JsonUtil.toHashMap(json);
        int pageSize = 10;
        int page = ((int) param.get("page") - 1) * pageSize;

        Specification specification = new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                String userId = param.get("sk").toString();
                if(org.apache.commons.lang.StringUtils.isNotBlank(userId)){
                    predicates.add(criteriaBuilder.equal(root.get("userId"),Long.valueOf(userId)));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };

        Page<Released> result= releasedRespository.findAll(specification,new PageRequest(page,pageSize));
        if (result.getContent().size()>0){
            for (Released released:result.getContent()) {
                if (released.getDeparture().length()>5){
                    released.setDeparture(released.getDeparture().substring(0,5)+"...");
                }
                if (released.getDestination().length()>5){
                    released.setDestination(released.getDestination().substring(0,5)+"...");
                }
            }
        }
        return new ReturnVO(result.getContent());
    }

    @POST
    @Path("getInfo")
    public ReturnVO getInfo(String json) {
        Map param = JsonUtil.toHashMap(json);
        Released released = releasedRespository.findOne(Long.valueOf(param.get("id").toString()));
        return new ReturnVO(released);
    }

    @POST
    @Path("getPrice")
    public ReturnVO getPrice(@Context HttpServletRequest request,String json){
        Map<String,String> param = JsonUtil.toHashMap(json);
        Map result = MapUtil.getDistanceByPoints(Double.valueOf(param.get("startlat")),Double.valueOf(param.get("startlng")),
                Double.valueOf(param.get("endlat")),Double.valueOf(param.get("endlng")));
        String sql = "SELECT * FROM sys_price WHERE id = 1";
        Map price = jdbcTemplate.queryForMap(sql);

        Double resultPrice = 0.00;

        //默认距离
        Double defaultDistance = 0.00;
        //距离内单价
        Double unitPrice = 0.00;

        //超出单价
        Double overstepPrice = 0.00;
        //1市内2跨城
        if (param.get("test").equals('1')){
            //默认距离
            defaultDistance = new BigDecimal(price.get("c_distance").toString()).multiply(new BigDecimal(1000)).doubleValue();
            //距离内单价
            unitPrice = Double.valueOf(price.get("city").toString());
            //超出单价
            overstepPrice = Double.valueOf(price.get("city_e").toString());
        }else {
            //默认距离
            defaultDistance = new BigDecimal(price.get("c_distance").toString()).multiply(new BigDecimal(1000)).doubleValue();
            //距离内单价
            unitPrice = Double.valueOf(price.get("city").toString());
            //超出单价
            overstepPrice = Double.valueOf(price.get("city_e").toString());
        }

        //实际距离
        Double actualDistance = Double.valueOf(result.get("distance").toString());


        //判断是否在距离内
        if (actualDistance > defaultDistance){
            //距离内价格
            BigDecimal u = new BigDecimal(unitPrice);
            BigDecimal b = new BigDecimal(defaultDistance);

            //超出的价格
            BigDecimal o = new BigDecimal(overstepPrice);
            BigDecimal c = new BigDecimal(actualDistance);
            resultPrice = ((u.multiply(b)).add(c.subtract(b).multiply(o))).divide(new BigDecimal(1000),2).doubleValue();

        }else {
            BigDecimal a = new BigDecimal(unitPrice);
            BigDecimal b = new BigDecimal(actualDistance);
            resultPrice = (a.multiply(b)).divide(new BigDecimal(1000),2).doubleValue();
        }
        return  new ReturnVO(resultPrice);
    }
}
